package com.ruoyi.auth.integration.authenticator.third;

import com.ruoyi.auth.api.model.dto.UserLoginInfoDto;
import com.ruoyi.auth.integration.IntegrationAuthentication;
import com.ruoyi.auth.integration.authenticator.IntegrationAuthenticator;
import com.ruoyi.auth.service.UserLoginInfoServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * 小程序集成认证
 *
 * @author LIQIU
 * @date 2018-3-31
 **/
@Service
public class ThirdIntegrationAuthenticator implements IntegrationAuthenticator {

    @Autowired
    @Lazy
    private PasswordEncoder passwordEncoder;

    @Autowired
    public UserLoginInfoServiceImpl userLoginInfoServiceImpl;

    private final static String AUTH_TYPE = "thirdLogin";

    @Override
    public UserLoginInfoDto authenticate(IntegrationAuthentication integrationAuthentication) {
        //获取授权类别
        String userCategory = integrationAuthentication.getUserCategory();
        //获取密码，实际值是验证码
        String password = integrationAuthentication.getAuthParameter("password");
        String appType = integrationAuthentication.getAuthParameter("app_type");
        String thirdCode = integrationAuthentication.getAuthParameter("third_code");
        String inviteCode = integrationAuthentication.getAuthParameter("invite_code");
        UserLoginInfoDto userLoginInfoDto = userLoginInfoServiceImpl.getUserApiService(userCategory).getUserInfoByThird(null, appType, thirdCode, inviteCode);
        if (userLoginInfoDto != null) {
            if (password == null) {
                userLoginInfoDto.setPassword(null);
            } else {
                userLoginInfoDto.setPassword(passwordEncoder.encode(password));
            }
        }
        return userLoginInfoDto;
    }

    @Override
    public void prepare(IntegrationAuthentication integrationAuthentication) {

    }

    @Override
    public boolean support(IntegrationAuthentication integrationAuthentication) {
        return AUTH_TYPE.equals(integrationAuthentication.getAuthType());
    }

    @Override
    public void complete(IntegrationAuthentication integrationAuthentication) {

    }
}
